Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/%22script.js/%22https:/cdn.jsdelivr.net/npm/@editorjs/table@latest/$%7BurlMatch[0]%7D?q=function&page=1&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 40716 results for "function"(2249ms)

quadratic-mcpmain.ts1 match

@jimnielsโ€ขUpdated 29 mins ago
51
52// ---------- Handler ----------
53export default async function (req: Request): Promise<Response> {
54 // Handle CORS preflight requests
55 if (req.method === "OPTIONS") {

untitled-9994upload.ts1 match

@reckterโ€ขUpdated 30 mins ago
11
12
13export default async function (req: Request): Promise<Response> {
14 const searchParams = new URL(req.url).searchParams
15 const gig = searchParams.get("gig")

Notesmain.tsx18 matches

@jsonโ€ขUpdated 35 mins ago
1export default function () {
2 const body = `<!doctype html>
3<html lang="en">
101
102 /************************************************************************
103 * State: raw variables & functions, and evaluated variables
104 ************************************************************************/
105 const rawVars = new Map(); // name -> rhs string (raw)
106 const functions = new Map(); // name -> { params: [], body: "..." }
107 const computedVars = new Map(); // name -> evaluated value (primitive, array, string, etc)
108
110 * Helpers
111 ************************************************************************/
112 function isQuotedString(s) {
113 return (s.length >= 2) && ((s[0] === '"' && s[s.length-1] === '"') || (s[0] === "'" && s[s.length-1] === "'"));
114 }
115
116 function toObj(map) {
117 const o = Object.create(null);
118 for (const [k,v] of map.entries()) o[k] = v;
120 }
121
122 function parseRange(s) {
123 const m = s.match(/(\\d+(?:\\.\\d+)?)\\s*(am|pm)?\\s*[\\โ€“\\-]\\s*(\\d+(?:\\.\\d+)?)\\s*(am|pm)?/i);
124 if (!m) return Number(s); // fallback if plain number
149 // Evaluate an expression string in a sandbox that includes:
150 // - current computedVars
151 // - user functions (as JS functions that evaluate their bodies with the same sandbox + parameters)
152 // - builtins
153 // - automatic range parsing
154 function evalWithScope(expr) {
155 // First, replace any range patterns with their numeric values
156 const processedExpr = expr.replace(/(\\d+(?:\\.\\d+)?)\\s*(am|pm)?\\s*[\\โ€“\\-]\\s*(\\d+(?:\\.\\d+)?)\\s*(am|pm)?/gi, (match) => {
159
160 const scope = Object.assign({}, builtins, toObj(computedVars));
161 for (const [name, def] of functions.entries()) {
162 scope[name] = (...args) => {
163 const local = Object.assign({}, scope);
164 def.params.forEach((p, i) => { local[p] = args[i]; });
165 return Function('scope','with(scope){return ('+def.body+')}')(local);
166 };
167 }
168
169 try {
170 let val = Function('scope','with(scope){return ('+processedExpr+')}')(scope);
171 return val;
172 } catch (e) { throw e; }
175 /************************************************************************
176 * Parse the document top-down:
177 * - function defs f(a,b)=...
178 * - variable defs name = rhs (rhs may be quoted string OR an expression)
179 *
180 * We evaluate variables in document order so earlier defs are available to later ones.
181 ************************************************************************/
182 function parseDocument(doc) {
183 rawVars.clear();
184 functions.clear();
185 computedVars.clear();
186
190 if (!line) continue;
191
192 // function: name(arg1, arg2) = body
193 const fm = line.match(/^([A-Za-z_][\\w]*)\\s*\\(([^)]*)\\)\\s*=\\s*(.+)$/);
194 if (fm) {
196 const params = fm[2].split(',').map(s=>s.trim()).filter(Boolean);
197 const body = fm[3].trim();
198 functions.set(name, { params, body });
199 continue;
200 }
207 rawVars.set(name, rhs);
208
209 // attempt to evaluate using current environment (earlier vars + functions)
210 try {
211 let value;
314 }, { decorations: v => v.decorations });
315
316 function stringifyValue(v) {
317 if (v === null || v === undefined) return String(v);
318 if (typeof v === 'number') {

val-town-http-mcp-servervtCli.ts9 matches

@charmaineโ€ขUpdated 38 mins ago
8 * @returns Promise resolving to boolean indicating CLI availability
9 */
10export async function isVtCliAvailable(): Promise<boolean> {
11 try {
12 const command = new Deno.Command("which", {
30 * @returns Promise resolving to boolean indicating CLI availability
31 */
32export async function getCliAvailability(): Promise<boolean> {
33 if (_isCliAvailable === null) {
34 _isCliAvailable = await isVtCliAvailable();
42 * @returns Promise resolving to an object containing command execution result
43 */
44export async function runVtCommand(args: string[]): Promise<{
45 success: boolean;
46 output: string;
71
72/**
73 * Parse CLI JSON output (placeholder for missing function)
74 * @param output CLI output string to parse
75 * @returns Parsed JSON object or error
76 */
77export function parseCliJsonOutput(output: string): any {
78 try {
79 return JSON.parse(output);
84
85/**
86 * Prepare Val workspace (placeholder for missing function)
87 * @param valId Val ID to prepare workspace for
88 * @returns Workspace preparation result
89 */
90export async function prepareValWorkspace(valId: string): Promise<{
91 success: boolean;
92 workspacePath?: string;
102
103/**
104 * Cleanup temporary directory (placeholder for missing function)
105 * @param dirPath Directory path to cleanup
106 * @returns Cleanup result
107 */
108export async function cleanupTempDirectory(dirPath: string): Promise<{
109 success: boolean;
110 error?: string;

val-town-http-mcp-servervalsTools.ts1 match

@charmaineโ€ขUpdated 38 mins ago
6import {z} from "npm:zod"
7
8export function registerValTools(server: McpServer, config: Config) {
9 // Get val by username and val name
10 server.tool(

val-town-http-mcp-servervalley.txt11 matches

@charmaineโ€ขUpdated 38 mins ago
10- **Never bake in secrets into the code** - always use environment variables
11- Include comments explaining complex logic (avoid commenting obvious operations)
12- Follow modern ES6+ conventions and functional programming practices if possible
13
14## Types of triggers
21
22```ts
23export default async function (req: Request) {
24 return new Response("Hello World");
25}
35
36```ts
37export default async function () {
38 // Scheduled task code
39}
49
50```ts
51export default async function (email: Email) {
52 // Process email
53}
58## Val Town Standard Libraries
59
60Val Town provides several hosted services and utility functions.
61
62### Blob Storage
112```
113
114## Val Town Utility Functions
115
116Val Town provides several utility functions to help with common project tasks.
117
118### Importing Utilities
191โ”‚ โ”œโ”€โ”€ database/
192โ”‚ โ”‚ โ”œโ”€โ”€ migrations.ts # Schema definitions
193โ”‚ โ”‚ โ”œโ”€โ”€ queries.ts # DB query functions
194โ”‚ โ”‚ โ””โ”€โ”€ README.md
195โ”‚ โ””โ”€โ”€ routes/ # Route modules
210โ””โ”€โ”€ shared/
211 โ”œโ”€โ”€ README.md
212 โ””โ”€โ”€ utils.ts # Shared types and functions
213```
214
217- Hono is the recommended API framework
218- Main entry point should be `backend/index.ts`
219- **Static asset serving:** Use the utility functions to read and serve project files:
220 ```ts
221 import { readFile, serveFile } from "https://esm.town/v/std/utils@85-main/index.ts";
251- Run migrations on startup or comment out for performance
252- Change table names when modifying schemas rather than altering
253- Export clear query functions with proper TypeScript typing
254
255## Common Gotchas and Solutions

val-town-http-mcp-servervalley_local.txt3 matches

@charmaineโ€ขUpdated 38 mins ago
6## Understanding Val Town
7
8Val Town is a platform for writing, running, and deploying JavaScript/TypeScript code in the cloud. It functions as a social coding environment where users can create and share code that runs on Val Town's serverless infrastructure.
9
10### Val Town Projects
21## Core Guidelines
22
23- Provide complete, functional solutions
24- Test logic against edge cases
25- Follow Val Town's platform requirements
26- Write clean, maintainable TypeScript/TSX code
27- Add appropriate TypeScript types for all data structures
28- Prefer functional programming practices where appropriate
29
30## Coding Requirements

val-town-http-mcp-serveruserTools.ts1 match

@charmaineโ€ขUpdated 38 mins ago
5import {getErrorMessage} from "../lib/errorUtils.ts"
6
7export function registerUserTools(server: McpServer, config: Config) {
8 // Get user information by username
9 server.tool(

val-town-http-mcp-servertownie.txt17 matches

@charmaineโ€ขUpdated 38 mins ago
10 1. `http`: http vals export a default server request handler.
11 2. `script`: script vals can be imported into other vals, similar to an npm package.
12 3. `cron`: cron vals export a function that can automatically run at user-set intervals, similar to a cron command.
13 4. `email`: email vals export a function that runs when its associated email address receives an email.
14
15Follow these requirements for Val Town when generating code.
49</requirements>
50
51If the user asks for specific functionality, the Val Town standard library includes the following:
52
53<libraries>
63 ```
64
65 Blob storage only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
66 `const { blob } = await import("https://esm.town/v/std/blob");`
67 </library>
78 If you are changing a SQLite table's schema, you should also change the table's name so it creates a fresh table, ie by adding _2 or _3 after it everywhere. Ensure that tables are created before they are used.
79
80 SQLite storage only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
81 `const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");`
82 </library>
99 ```
100
101 OpenAI only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
102 `const { OpenAI } = await import "https://esm.town/v/std/openai");`
103 </library>
113 ```
114
115 Email only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
116 `const { email } = await import "https://esm.town/v/std/email");`
117 </library>
131 Write the code in ```val code fences.
132 Include the val type as metadata on the code fence, e.g.: ```val type=script
133 If this is a new val, decide what val type is appropriate based on the user's prompt. Default to choosing http type vals unless the user has requested specific functionality that requires a different type.
134
135 * If the user requests diff format in their prompt, follow these steps:
157 * Use fetch to communicate with the backend server portion.
158 */
159function App() {
160 return (
161 <div>
167/**
168 * Client-only code
169 * Any code that makes use of document or window should be scoped to the `client()` function.
170 * This val should not cause errors when imported as a module in a browser.
171 */
172function client() {
173 createRoot(document.getElementById("root")).render(<App />);
174}
177/**
178 * Server-only code
179 * Any code that is meant to run on the server should be included in the server function.
180 * This can include endpoints that the client side component can send fetch requests to.
181 */
182export default async function server(request: Request): Promise<Response> {
183 /** If needed, blob storage or sqlite can be imported as a dynamic import in this function.
184 * Blob storage should never be used in the browser directly.
185 * Other server-side specific modules can be imported in a similar way.
232 ```val type=script
233 /** Use this template for creating script vals only */
234 export default function () {
235 return "Hello, world";
236 }
243 ```val type=cron
244 /** Use this template for creating cron vals only */
245 export default async function (interval: Interval) {
246 // code will run at an interval set by the user
247 console.log(`Hello, world: ${Date.now()}`);
270 // The email address for this val will be `<username>.<valname>@valtown.email` which can be derived from:
271 // const emailAddress = new URL(import.meta.url).pathname.split("/").slice(-2).join(".") + "@valtown.email";
272 export default async function (e: Email) {
273 console.log("Email received!", email.from, email.subject, email.text);
274 }

val-town-http-mcp-serversqliteTools.ts3 matches

@charmaineโ€ขUpdated 38 mins ago
5import {getErrorMessage} from "../lib/errorUtils.ts"
6
7export function registerSqliteTools(server: McpServer, config: Config) {
8 // Execute SQL
9 server.tool(
64 )
65
66 // Fix for sqlite-query function
67 server.tool(
68 "sqlite-query",
91 )
92
93 // Fix for sqlite-exec function
94 server.tool(
95 "sqlite-exec",

ratelimit4 file matches

@unkeyโ€ขUpdated 1 month ago
Rate limit your serverless functions

discordWebhook2 file matches

@stevekrouseโ€ขUpdated 2 months ago
Helper function to send Discord messages
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.